package com.example.swing;

import javax.swing.*;
import java.awt.*;

public class LcsVisualizer extends JPanel {

    private final String[] A = {"a", "b", "c", "d"};
    private final String[] B = {"a", "e", "c", "f"};
    private final int[][] dp;

    public LcsVisualizer() {
        dp = computeLCSMatrix(A, B);
        setPreferredSize(new Dimension(600, 400));
    }

    private int[][] computeLCSMatrix(String[] A, String[] B) {
        int[][] dp = new int[A.length + 1][B.length + 1];
        for (int i = 1; i <= A.length; i++) {
            for (int j = 1; j <= B.length; j++) {
                if (A[i - 1].equals(B[j - 1])) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        return dp;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        int cellSize = 60;
        g.setFont(new Font("Monospaced", Font.PLAIN, 14));

        // Draw header
        for (int j = 0; j <= B.length; j++) {
            String text = (j == 0) ? "" : B[j - 1];
            g.drawString(text, 80 + j * cellSize, 40);
        }

        for (int i = 0; i <= A.length; i++) {
            String text = (i == 0) ? "" : A[i - 1];
            g.drawString(text, 40, 80 + i * cellSize);
        }

        // Draw grid
        for (int i = 0; i <= A.length; i++) {
            for (int j = 0; j <= B.length; j++) {
                int x = 60 + j * cellSize;
                int y = 60 + i * cellSize;

                g.drawRect(x, y, cellSize, cellSize);
                g.drawString(String.valueOf(dp[i][j]), x + 20, y + 35);

                // Draw arrow (simple demo: ↖ if equal, ↑ or ← otherwise)
                if (i > 0 && j > 0) {
                    if (A[i - 1].equals(B[j - 1])) {
                        g.drawString("↖", x + 40, y + 20);
                    } else if (dp[i - 1][j] >= dp[i][j - 1]) {
                        g.drawString("↑", x + 40, y + 20);
                    } else {
                        g.drawString("←", x + 40, y + 20);
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("LCS Visualizer");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new LcsVisualizer());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

